"use strict";
//images
import logo from "../../static/img/h5/logo.png"
import weixin from "../../static/img/h5/weixin.png"
import weibo from "../../static/img/h5/weibo.png"
import qq from "../../static/img/h5/qq.png"

//=============
// 引入程序依赖
//=============
import React, { Component } from 'react' ;
import { connect } from 'react-redux' ;
import { mapStateToProps, mapDispatchToProps } from './LoginRedux' ;
import { Link, browserHistory } from 'react-router' ;

//交互依赖
import NetworkEngine from '../../utils/NetworkEngine' ;
import UrlManager from '../../utils/UrlManager' ;
import gantan from "../../static/img/h5/gantan.png";

//style
import "./Login.scss" ;
import "../../utils/flexible/flexible.debug"

class LoginContainer extends Component {
    constructor(props) {
        super(props);
    }

    state = {
        clientIp : "",
    }

    componentDidMount() {
        $(this.refs.bg).parents("body").css("background","#fff");
        this.state.clientIp = window.location.hostname;
        this.initGeetestFun();
    }

    //geetestAPI1
    initGeetestFun() {
        const _this = this;
        let urlManager = new UrlManager();
        NetworkEngine(
            "post",
            urlManager.initGeetest(),
            {
                userId: sessionStorage.getItem("id") ? sessionStorage.getItem("id") : "",
                clientType: "h5",
                clientIp: this.state.clientIp ? this.state.clientIp : null,
            }
        ).then(
            data => {
                let gtServerStatus = data.data.res.gt_server_status;
                let responseStr = data.data.res.responseStr;
                let userId = data.data.res.userId;
                let geetestData = JSON.parse(responseStr);
                initGeetest({
                    gt: geetestData.gt,
                    challenge: geetestData.challenge,
                    new_captcha: geetestData.new_captcha, // 用于宕机时表示是新验证码的宕机
                    offline: !geetestData.success, // 表示用户后台检测极验服务器是否宕机，一般不需要关注
                    product: 'float',
                    width: "100%",
                    // bg_color:"custom",
                    // 更多配置参数请参见：http://www.geetest.com/install/sections/idx-client-sdk.html#config
                }, function (captchaObj) {
                    _this.state.captchaObj = captchaObj;
                    $("#submit1").click(function (e) {
                        var result = captchaObj.getValidate();
                        //验证不通过时
                        if (!result) {
                            let phone = _this.refs.phone.value ;
                            let password = _this.refs.password.value;
                            if (_this.checkIsNull(phone,password)) {
                                _this.showErrorInfo("请进行验证")
                            };
                        } else {
                            //验证通过时,进入二次验证
                            result.gtServerStatus = gtServerStatus;
                            _this.login(result);
                        }
                    });
                    // 将验证码加到id为captcha的元素里，同时会有三个input的值用于表单提交
                    captchaObj.appendTo("#captcha1");

                    captchaObj.onReady(function () {
                        $("#wait1").hide();
                    });

                    captchaObj.onSuccess(function() {
                        _this.state.currentPhone = _this.refs.phone.value;
                        _this.state.currentPassword = _this.refs.password.value;
                        $(_this.refs.gtError).hide();
                        // var result = captchaObj.getValidate();
                        // result.gtServerStatus = gtServerStatus;
                        // _this.login(result);
                    });
                });
            }
        ).catch(
            err => {

            }
        )
    }

    //检查用户名和密码
    checkIsNull(phone,password){
        if (phone && password) {
            return true;
        }
        if (!phone && !password) {
            //电话密码都为空
            $(this.refs.phone).removeClass("red-border");
            $(this.refs.password).removeClass("red-border");
            $(this.refs.Error).show();
            $(this.refs.phone).addClass("red-border");
            $(this.refs.passwordError).hide();
            $(this.refs.eeError).hide();
            $(this.refs.passwordwrongError).hide();
            $(this.refs.pError).hide();
            $(this.refs.gtError).hide();
            return false;
        } else if (phone) {
            //密码为空 电话不为空
            $(this.refs.phone).removeClass("red-border");
            $(this.refs.password).removeClass("red-border");
            $(this.refs.Error).hide();
            $(this.refs.passwordError).show();
            $(this.refs.password).addClass("red-border");
            $(this.refs.eeError).hide();
            $(this.refs.passwordwrongError).hide();
            $(this.refs.pError).hide();
            $(this.refs.gtError).hide();
            return false;
        } else if (password) {
            //电话为空 密码不为空
            $(this.refs.phone).removeClass("red-border");
            $(this.refs.password).removeClass("red-border");
            $(this.refs.Error).hide();
            $(this.refs.passwordError).hide();
            $(this.refs.eeError).hide();
            $(this.refs.passwordwrongError).hide();
            $(this.refs.phone).addClass("red-border");
            $(this.refs.pError).show();
            $(this.refs.gtError).hide();
            return false;
        }
    }

    login(verifyObj){
        // e.preventDefault();
        let phone = this.refs.phone.value ;
        let password = this.refs.password.value;
        let urlManager = new UrlManager() ;

        //密码或者电话修改后重新验证
        if (phone != this.state.currentPhone || password != this.state.currentPassword) {
            this.state.captchaObj.reset();
            this.showErrorInfo("登录信息已更改，请您点击按钮重新验证");
            return ;
        }

        //拼凑参数
        let param = {
            phone : phone,
            password : password,
            userId: sessionStorage.getItem("id") ? sessionStorage.getItem("id") : "",
            clientType: "h5",
            clientIp: this.state.clientIp ? this.state.clientIp : null,
            fnGeetestChallenge: verifyObj.geetest_challenge,
            fnGeetestValidate: verifyObj.geetest_validate,
            fnGeetestSeccode: verifyObj.geetest_seccode,
            gtServerStatus: verifyObj.gtServerStatus,
        }
        NetworkEngine(
            "post",
            urlManager.mobileLogin(),param
        ).then(
            data=> {
                let resData = data.data;
                if (resData.status == "0") {
                    let _data = resData.data;
                    sessionStorage.setItem("id", _data.id);
                    sessionStorage.setItem("userKeyId",_data.updatedUser);
                    sessionStorage.setItem("displayName", _data.displayName);
                    sessionStorage.setItem("phone", _data.phone);
                    sessionStorage.setItem("authenticationStatus", _data.authenticationStatus);
                    sessionStorage.setItem("headUrl", _data.headUrl);
                    sessionStorage.setItem("viewerKey",_data.createdUser);
                    if(localStorage.getItem("useFilmId")!=undefined){
                        window.location.href="/App/FilmDetail/"+ localStorage.getItem("useFilmId");
                        localStorage.removeItem("useFilmId");
                    } else if (localStorage.getItem("taskId")) {
                        window.location.href="/App/DemandDetail/"+ localStorage.getItem("taskId");
                        localStorage.removeItem("taskId");
                    } else {
                        browserHistory.push("/APP/MobileHome");
                    }
                } else if (resData.status == "1") {
                    let errorMes = resData.error_message + '';
                    //重置极验证
                    this.state.captchaObj.reset();
                    if (errorMes.startsWith("geetestFail")) {
                        //极验证失败
                        let mes = errorMes.split("geetestFail")[1];
                        this.showErrorInfo(mes);
                    } else if (phone == "" && password == "") {
                        $(this.refs.phone).removeClass("red-border");
                        $(this.refs.password).removeClass("red-border");
                        $(this.refs.Error).show();
                        $(this.refs.phone).addClass("red-border");
                        $(this.refs.passwordError).hide();
                        $(this.refs.eeError).hide();
                        $(this.refs.passwordwrongError).hide();
                        $(this.refs.pError).hide();
                        $(this.refs.gtError).hide();
                    } else if (phone == this.refs.phone.value && phone != "" && password == "") {
                        $(this.refs.phone).removeClass("red-border");
                        $(this.refs.password).removeClass("red-border");
                        $(this.refs.Error).hide();
                        $(this.refs.passwordError).show();
                        $(this.refs.password).addClass("red-border");
                        $(this.refs.eeError).hide();
                        $(this.refs.passwordwrongError).hide();
                        $(this.refs.pError).hide();
                        $(this.refs.gtError).hide();
                    } else if (phone == this.refs.phone.value && phone != "" && password != "") {
                        $(this.refs.phone).removeClass("red-border");
                        $(this.refs.password).removeClass("red-border");
                        $(this.refs.Error).hide();
                        $(this.refs.passwordError).hide();
                        $(this.refs.eeError).hide();
                        $(this.refs.passwordwrongError).show();
                        $(this.refs.password).addClass("red-border");
                        $(this.refs.pError).hide();
                        $(this.refs.gtError).hide();
                    } else if (phone != this.refs.phone.value && phone != "" && password != "") {
                        $(this.refs.phone).removeClass("red-border");
                        $(this.refs.password).removeClass("red-border");
                        $(this.refs.Error).hide();
                        $(this.refs.passwordError).hide();
                        $(this.refs.eeError).show();
                        $(this.refs.phone).addClass("red-border");
                        $(this.refs.passwordwrongError).hide();
                        $(this.refs.pError).hide();
                        $(this.refs.gtError).hide();
                    } else if ( phone == "" && password != "") {
                        $(this.refs.phone).removeClass("red-border");
                        $(this.refs.password).removeClass("red-border");
                        $(this.refs.Error).hide();
                        $(this.refs.passwordError).hide();
                        $(this.refs.eeError).hide();
                        $(this.refs.passwordwrongError).hide();
                        $(this.refs.pError).show();
                        $(this.refs.phone).addClass("red-border");
                        $(this.refs.gtError).hide();
                    }
                }
            }
        ).catch(
            err=>{
            }
        )
        MtaH5.clickStat('H5_Regis_003');
    }

    //展示geetest错误信息
    showErrorInfo(mes){
        $(this.refs.phone).removeClass("red-border");
        $(this.refs.password).removeClass("red-border");
        $(this.refs.gtErrorMes).text(mes)
        $(this.refs.gtError).show();
        // $(this.refs.phone).addClass("red-border");
        $(this.refs.Error).hide();
        $(this.refs.passwordError).hide();
        $(this.refs.eeError).hide();
        $(this.refs.passwordwrongError).hide();
        $(this.refs.pError).hide();
    }

    // login(e){
    //     MtaH5.clickStat('H5_Regis_003');
    //     e.preventDefault();
    //     let phone = this.refs.phone.value ;
    //     let password = this.refs.password.value;
    //         let urlManager = new UrlManager() ;
    //         NetworkEngine(
    //             "post",
    //             urlManager.mobileLogin(),
    //             {
    //                 phone : phone,
    //                 password : password ,
    //                 gtServerStatus : -1589,
    //             }
    //         ).then(
    //             data=> {
    //                 let _data = data.data;
    //                 console.log("=======登陆======", data.data)
    //                     if (data.data.status == "0") {
    //                         console.log("=======wwwwwwwww======",data.data.data)
    //                         let _data = data.data.data;
    //                         sessionStorage.setItem("id", _data.id);
    //                         sessionStorage.setItem("userKeyId",_data.updatedUser);
    //                         sessionStorage.setItem("displayName", _data.displayName);
    //                         sessionStorage.setItem("phone", _data.phone);
    //                         sessionStorage.setItem("authenticationStatus", _data.authenticationStatus);
    //                         sessionStorage.setItem("headUrl", _data.headUrl);
    //                         if(localStorage.getItem("useFilmId")!=undefined){
    //                             window.location.href="/App/FilmDetail/"+ localStorage.getItem("useFilmId");
    //                             localStorage.removeItem("useFilmId");
    //                         } else if (localStorage.getItem("taskId")) {
    //                             window.location.href="/App/DemandDetail/"+ localStorage.getItem("taskId");
    //                             localStorage.removeItem("taskId");
    //                         } else {
    //                             browserHistory.push("/APP/MobileHome");
    //                         }
    //                     } else if (_data.status == "1") {
    //                         if (phone == "" && password == "") {
    //                             $(this.refs.phone).removeClass("red-border");
    //                             $(this.refs.password).removeClass("red-border");
    //                             $(this.refs.Error).show();
    //                             $(this.refs.phone).addClass("red-border");
    //                             $(this.refs.passwordError).hide();
    //                             $(this.refs.eeError).hide();
    //                             $(this.refs.passwordwrongError).hide();
    //                             $(this.refs.pError).hide();
    //                         } else if (phone == this.refs.phone.value && phone != "" && password == "") {
    //                             $(this.refs.phone).removeClass("red-border");
    //                             $(this.refs.password).removeClass("red-border");
    //                             $(this.refs.Error).hide();
    //                             $(this.refs.passwordError).show();
    //                             $(this.refs.password).addClass("red-border");
    //                             $(this.refs.eeError).hide();
    //                             $(this.refs.passwordwrongError).hide();
    //                             $(this.refs.pError).hide();
    //                         } else if (phone == this.refs.phone.value && phone != "" && password != "") {
    //                             $(this.refs.phone).removeClass("red-border");
    //                             $(this.refs.password).removeClass("red-border");
    //                             $(this.refs.Error).hide();
    //                             $(this.refs.passwordError).hide();
    //                             $(this.refs.eeError).hide();
    //                             $(this.refs.passwordwrongError).show();
    //                             $(this.refs.password).addClass("red-border");
    //                             $(this.refs.pError).hide();
    //                         } else if (phone != this.refs.phone.value && phone != "" && password != "") {
    //                             $(this.refs.phone).removeClass("red-border");
    //                             $(this.refs.password).removeClass("red-border");
    //                             $(this.refs.Error).hide();
    //                             $(this.refs.passwordError).hide();
    //                             $(this.refs.eeError).show();
    //                             $(this.refs.phone).addClass("red-border");
    //                             $(this.refs.passwordwrongError).hide();
    //                             $(this.refs.pError).hide();
    //                         } else if ( phone == "" && password != "") {
    //                             $(this.refs.phone).removeClass("red-border");
    //                             $(this.refs.password).removeClass("red-border");
    //                             $(this.refs.Error).hide();
    //                             $(this.refs.passwordError).hide();
    //                             $(this.refs.eeError).hide();
    //                             $(this.refs.passwordwrongError).hide();
    //                             $(this.refs.pError).show();
    //                             $(this.refs.phone).addClass("red-border");
    //                         }
    //                     }
    //                 }
    //         ).catch(
    //             err=>{
    //             }
    //         )
    // }

    setThirdType(param){
        //第三方的type  微信-1 微博-2 QQ-3
        sessionStorage.setItem("thirdType",param);
    }
    render(){
        return(
            <div className="login-form" ref="bg" style={{background:"#fff"}}>
                <div className="logo">< img src={logo} alt="咪吱logo"/></div>
                <div className="container">
                    <div className="input-f username">
                        <input type="text" className="input" ref="phone" placeholder="手机号"/>
                        <div className="re-error" ref="Error">
                            < img src={gantan} alt="图标"/>
                            请输入电话号码和密码
                        </div>
                        <div className="re-error" ref="pError">
                            < img src={gantan} alt="图标"/>
                            请输入电话号码
                        </div>
                        <div className="re-error" ref="eeError">
                            < img src={gantan} alt="图标"/>
                            该用户不存在，请先注册
                        </div>
                    </div>
                    <div className="input-f">
                        <input type="password" className="input" ref="password" placeholder="密码"/>
                        <div className="re-error" ref="passwordwrongError">
                            < img src={gantan} alt="图标"/>
                            密码错误
                        </div>
                        <div className="re-error" ref="passwordError">
                            < img src={gantan} alt="图标"/>
                            请输入密码
                        </div>
                    </div>
                    <div className="form-a"><Link to="/MobileModifyPsw1" className="a-link1">忘记密码?</Link></div>
                    <div className="form-geetest-item">
                        <div className="captcha">
                            <p id={"wait1"} className="show">正在加载验证码......</p>
                            <div id={"captcha1"}>
                            </div>
                        </div>
                        <div className="form-wrong-geetest" ref="gtError">
                            <img className="wrong-img" src={gantan} alt="感叹"/>
                            <span className="wrong-geetest" ref="gtErrorMes">请点击进行验证</span>
                        </div>
                    </div>
                    <button type="btn"
                            id="submit1"
                        // onClick={this.login.bind(this)}
                            className="form-btn1 orange-btn">登录</button>
                    <span className="form-a margin-1" href="logon.html">还没有账号，<Link to="/Regis" className="logon">注册新账号</Link></span>
                </div>
                {/*<div className="three" >*/}
                {/*<div className="three-top">*/}
                {/*<p className="bor"></p>*/}
                {/*<p className="text">其他登录方式</p>*/}
                {/*<p className="bor"></p>*/}
                {/*</div>*/}
                {/*<div className="three-bottom">*/}
                {/*<div className="weixin">*/}
                {/*<a target="_blank" onClick={this.setThirdType.bind(this, "1")}*/}
                {/*href="https://open.weixin.qq.com/connect/qrconnect?appid=wx4002b019d6429df6&redirect_uri=http://www.mizhimedia.com/BindingPhone&response_type=code&scope=snsapi_login&state=weixin2">*/}
                {/*<img src={weixin} alt="微信"/>*/}
                {/*</a>*/}
                {/*</div>*/}
                {/*<div className="weibo">*/}
                {/*<a target="_blank" onClick={this.setThirdType.bind(this, "2")}*/}
                {/*href="https://api.weibo.com/oauth2/authorize?client_id=453780620&redirect_uri=http://www.mizhimedia.com/BindingPhone&state=weibo2">*/}
                {/*<img src={weibo} alt="微博"/>*/}
                {/*</a>*/}
                {/*</div>*/}
                {/*<div className="qq">*/}
                {/*<a target="_blank" onClick={this.setThirdType.bind(this,"3")}*/}
                {/*href="https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101424832&redirect_uri=http://www.mizhimedia.com/BindingPhone&state=QQ2">*/}
                {/*<img src={qq} alt="qq"/>*/}
                {/*</a>*/}
                {/*</div>*/}
                {/*</div>*/}
                {/*</div>*/}
            </div>
        )
    }
}

const Login = connect(mapStateToProps,mapDispatchToProps)(LoginContainer) ;

export { Login as default } ;

